package com.tinysand.advert.index.impl;

import com.tinysand.advert.index.IndexAware;
import com.tinysand.advert.index.support.AdvertObject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created By TINY
 * Create Time 2020/2/27
 **/
@Component
public class AdvertIndex
        implements IndexAware<Long, AdvertObject> {

    private static Map<Long, AdvertObject> objectMap;

    static {
        objectMap = new ConcurrentHashMap<>();
    }

    public List<AdvertObject> fetch(Collection<Long> adIds) {
        if (CollectionUtils.isEmpty(adIds)) {
            return Collections.emptyList();
        }

        List<AdvertObject> result = new ArrayList<>();
        adIds.forEach(a -> {
            AdvertObject object = get(a);
            if (null == object) {
                return;
            }
            result.add(object);
        });
        return result;
    }

    @Override
    public AdvertObject get(Long key) {
        return objectMap.get(key);
    }

    @Override
    public void add(Long key, AdvertObject value) {
        objectMap.put(key, value);
    }

    @Override
    public void update(Long key, AdvertObject value) {
        AdvertObject oldObject = objectMap.get(key);
        if (null == oldObject) {
            objectMap.put(key, value);
        } else {
            oldObject.update(value);
        }
    }

    @Override
    public void delete(Long key, AdvertObject value) {
        objectMap.remove(key, value);
    }
}
